package glin

import (
	"fmt"
	"os"
	"path/filepath"

	"gitee.com/zhangycsz/glin/systemd"
)

//实现服务器进程运行

type program struct {
	Status         string
	systemdOnStart func(string)
	systemdOnStop  func(string)
}

func (p *program) Start(s systemd.Service) error {
	//fmt.Println("Service is starting...")
	go p.run()
	return nil
}

func (p *program) run() {
	// 在这里编写你的业务逻辑
	//fmt.Println("Service is running...")
	p.systemdOnStart(p.Status)
}

func (p *program) Stop(s systemd.Service) error {
	// 在这里编写停止逻辑
	//fmt.Println("Service is stopping...")
	p.systemdOnStop("stop")
	return nil
}

// 开始服务进程入口
// displayName 简单描述应用,
// description 详细描述应用,
// onStart 启动时回调,
// onStop 停止时回调,
func SystemdService(displayName, description string, onStart func(string), onStop func(string)) {
	paramName := ""
	if len(os.Args) > 0 {
		paramName = filepath.Base(os.Args[0])
	}

	svcConfig := &systemd.Config{
		Name:        paramName,
		DisplayName: displayName,
		Description: description,
	}

	prg := &program{
		systemdOnStart: onStart,
		systemdOnStop:  onStop,
	}
	s, err := systemd.New(prg, svcConfig)
	if err != nil {
		fmt.Errorf("new systemd启动失败", err)
		return
	}

	if len(os.Args) > 1 {
		cmd := os.Args[1]
		prg.Status = cmd
		switch cmd {
		case "install":
			err := s.Install()
			if err != nil {
				fmt.Errorf("install:", err)
				return
			}
			fmt.Println("Service installed successfully.")
		case "uninstall":
			err := s.Uninstall()
			if err != nil {
				fmt.Errorf("uninstall:", err)
				return
			}
			fmt.Println("Service uninstalled successfully.")
		case "start":
			err := s.Start()
			if err != nil {
				fmt.Errorf("Start:", err)
				return
			}
			fmt.Println("Service started successfully.")
		case "stop":
			err := s.Stop()
			if err != nil {
				fmt.Errorf("stop:", err)
				return
			}
			fmt.Println("Service stopped successfully.")
		case "config": //重新读取配置文件夹

			return
		case "restart":
			err := s.Restart()
			if err != nil {
				fmt.Errorf("restart:%s", err)
				return
			}
			fmt.Println("restart is running...")
		case "status":
			status, err := s.Status()
			if err != nil {
				fmt.Println(err)
			} else {
				switch status {
				case 0:
					fmt.Println("Service is not running...")
				case 1:
					fmt.Println("Service is running...")
				case 2:
					fmt.Println("Service is stopped...")
				}
			}
			return
		default:
			fmt.Println("Unknown command:", cmd)
		}
		return
	}

	err = s.Run()
	if err != nil {
		fmt.Errorf("启动失败:", err)
	}
}
